package com.zl.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zl.common.Result;
import com.zl.dto.TsRoleDto;
import com.zl.dto.TsRoleSmallDto;
import com.zl.dto.base.PaginationDto;
import com.zl.dto.base.TsPageInfoDto;
import com.zl.entity.TsRole;
import com.zl.entity.TsRolePermission;
import com.zl.mapper.RoleMapper;
import com.zl.mapper.RolePermissionMapper;
import com.zl.service.RoleService;
import javafx.scene.control.Pagination;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public Result create(TsRoleDto resources) {
        try {
            /*if(roleMapper.findByRolename(resources.getRolename())!=null){
                return Result.error("用户名已存在");
            }

            if(roleMapper.findByEmail(resources.getEmail())!=null){
                return Result.error("邮箱已存在");
            }*/
            // 默认密码 123456，此密码是加密后的字符
            /*resources.setPassword("e10adc3949ba59abbe56e057f20f883e");
            resources.setAvatar("https://i.loli.net/2019/04/04/5ca5b971e1548.jpeg");*/
            roleMapper.save(resources);
            return Result.success();
        } catch (Exception e) {
            log.error("用户新增失败");
            return Result.error();
        }
    }

    @Override
    public Result update(TsRoleDto resources) {
        return null;
    }

    @Override
    public Result delete(Long id) {
        return null;
    }

    @Override
    public List<TsRoleSmallDto> findByUsersId(Long id) {
        return roleMapper.findUsersId(id);
    }

    @Override
    public PaginationDto<TsRoleDto> findPaginationByName(String name, PaginationDto<TsRoleDto> p) {
        List<TsRoleDto> list= roleMapper.findPaginationByName(name, p);
        p.setList(list);
        return p;
    }

    @Override
    public PageInfo<TsRoleDto> queryAll(TsPageInfoDto params) {
        //将参数传给这个方法就可以实现物理分页了，非常简单。
        PageHelper.startPage(params.getPage(), params.getLimit());
        List<TsRole> fixedList = roleMapper.queryAll();
        for (TsRole r:fixedList) {
            if(r.getId()!=null){
//                r.setPermissions(rolePermissionMapper.findByRoleId(r.getId()).stream().map(TsRolePermission::getPermissionId).collect(Collectors.toList()));
            }
        }
        PageInfo result = new PageInfo(fixedList);
        return result;
    }
}
